# 身份验证路由
from flask import request, jsonify, g
from flask_jwt_extended import get_jwt_identity, create_access_token
from models import User, db
from utils.password_utils import check_password


def register_auth_routes(app):
    # 登录
    @app.route('/plantACR/login', methods=['POST'])
    def login():
        resultVO = {
            "code": 200,
            "data": {}
        }
        try:
            data = request.get_json()
            name = data.get('name')
            password = data.get('password')

            user = User.query.filter_by(name=name).first()
            if user and check_password(password, user.password):
                # 创建访问令牌
                access_token = create_access_token(identity={"id": user.id, "role": user.role})
                resultVO["message"] = '登录成功'
                resultVO["data"] = {
                    "role": user.role,
                    "user": {
                        "id": user.id,
                        "name": user.name,
                        # "password": user.password,  # 注意：这里返回的是加密后的密码
                        "role": user.role,
                        "create_time": user.create_time,
                        "update_time": user.update_time
                    },
                    "token": access_token
                }
                # return jsonify(resultVO)
                # 创建响应对象
                resp = jsonify(resultVO)
                # 将 token 添加到响应头中
                resp.headers['token'] = access_token
                return resp
            else:
                resultVO["code"] = 401
                resultVO["message"] = '用户名或密码错误！'
                return jsonify(resultVO)
        except Exception as e:
            db.session.rollback()
            print("登录异常信息：", e)
            resultVO["code"] = 500
            resultVO["message"] = "服务器异常，登录失败！"
            return jsonify(resultVO)

    # 测试
    @app.route('/test', methods=['GET'])
    def protected():

        resultVO = {
            "code": 200,
            "data": {}
        }
        try:
            resultVO["message"] = '测试成功'
            resultVO["data"] = {
                "result": "test success",
            }
            return jsonify(resultVO)
        except Exception as e:
            print("登录异常信息：", e)
            resultVO["code"] = 500
            resultVO["message"] = "异常,测试失败！"
            return jsonify(resultVO)

    return app
